package com.lam.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

public class RandomUtil {
	
	public static <T> T genByScale(Map<T, Object> scaleMap, T def) {
	
		if(CollectionUtil.isEmpty(scaleMap) || scaleMap.size() == 1) {
			return def;
		}
		
		int rangeMax = 0;
		int[] range = new int[scaleMap.size()];
		List<T> rangeVal = new ArrayList<>();
		int i = 0;
		for (Entry<T, Object> entry : scaleMap.entrySet()) {
			rangeMax += (NumberUtil.max(NumberUtil.toInt(entry.getValue()), 0));
			range[i] = rangeMax;
			rangeVal.add(entry.getKey());
			i++;
		}
		if(rangeMax < 1) {
			return def;
		}
		
		Random rand = new Random(System.currentTimeMillis()); 
		int index = rand.nextInt(rangeMax);
		for (i = 0; i < range.length; i++) {
			if(index <= range[i]) {
				return rangeVal.get(i);
			}
		}
		return def;
	}
	
	

}
